<template>
  <el-row class="p-5 pt-0" @keyup.enter="getSeaData">

    <el-col v-if="showSearch">
      <el-form :inline="true" :model="search" class="demo-form-inline">
        <el-form-item label="客户名称" class="font-black">
          <el-input v-model="search.name" :disabled="loading" :size="store.layoutSize" clearable style="width: 160px"
                    placeholder="请输入客户名称"/>
        </el-form-item>
        <el-form-item label="负责人" class="font-black">
          <el-input v-model="search.director" :disabled="loading" :size="store.layoutSize" clearable
                    style="width: 120px"
                    placeholder="请输入负责人"/>
        </el-form-item>
        <el-form-item label="客户来源" class="font-black">
          <el-select v-model="search.source" :disabled="loading" :size="store.layoutSize" clearable style="width: 100px"
                     placeholder="客户来源" @change="getSeaData">
            <el-option v-for="item in sourceData.data" :label="item.dictLabel" :value="item.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="客户性质" class="font-black">
          <el-select v-model="search.nature" :disabled="loading" :size="store.layoutSize" clearable style="width: 100px"
                     placeholder="客户性质" @change="getSeaData">
            <el-option v-for="item in natureData.data" :label="item.dictLabel" :value="item.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" class="font-black">
          <el-date-picker v-model="date"
                          :disabled="loading"
                          :shortcuts="shortcuts"
                          :size="store.layoutSize"
                          clearable
                          end-placeholder="结束日期"
                          range-separator="-"
                          start-placeholder="开始日期"
                          style="width: 210px"
                          type="daterange"
                          unlink-panels
                          value-format="YYYY-MM-DD"
                          @change="getSeaData"
          />
        </el-form-item>
        <el-form-item>
          <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" auto-insert-space
                     type="primary"
                     @click="getSeaData">
            <template #icon>
              <el-icon>
                <Search/>
              </el-icon>
            </template>
            查询
          </el-button>
          <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" auto-insert-space plain
                     @click="clearSearch">
            <template #icon>
              <el-icon>
                <Refresh/>
              </el-icon>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-col class="flex justify-between">
      <div>
        <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" auto-insert-space plain
                   type="primary"
                   @click="add">
          <template #icon>
            <el-icon>
              <Plus/>
            </el-icon>
          </template>
          新增
        </el-button>
        <el-button :disabled="search.total === 0 || loading" :size="store.layoutSize" auto-insert-space plain
                   type="warning"
                   @click="download">
          <template #icon>
            <el-icon>
              <Download/>
            </el-icon>
          </template>
          导出
        </el-button>
      </div>
      <div>
        <el-tooltip
            class="box-item"
            effect="dark"
            :content="showSearch?'隐藏搜索':'显示搜索'"
            placement="top"
        >
          <el-button :color="store.getTheme" :size="store.layoutSize" @click="showSearch = !showSearch"
                     circle>
            <el-icon>
              <Search/>
            </el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip
            class="box-item"
            effect="dark"
            content="刷新"
            placement="top"
        >
          <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" @click="getSeaData"
                     circle>
            <el-icon>
              <Refresh/>
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </el-col>

    <el-col class="mt-2">
      <el-table :size="store.layoutSize" v-loading="loading" element-loading-text="正在努力加载中..."
                :data="tableSeaData.data"
                style="width: 100%" table-layout="auto" row-key="id"
                @row-dblclick="rowClick"
                highlight-current-row empty-text="无数据">

        <el-table-column align="center" label="客户名称" min-width="130" prop="name"/>

        <el-table-column align="center" label="客户电话" min-width="130" prop="phone"/>

        <el-table-column align="center" label="性别">
          <template #default="scope">
            <el-tag :type="scope.row.sex === '1' ? 'danger':''">
              <span v-for="item in sexData.data" :key="item.dictCode"
                    v-show="scope.row.sex === item.dictValue">{{ item.dictLabel }}</span>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="年龄段">
          <template #default="scope">
            <el-tag type="info">
              <span v-for="item in agesData.data" :key="item.dictCode"
                    v-show="scope.row.age === item.dictValue">{{ item.dictLabel }}</span>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="客户来源">
          <template #default="scope">
            <el-tag type="warning">
              <span v-for="item in sourceData.data" :key="item.dictCode"
                    v-show="scope.row.source === item.dictValue">{{ item.dictLabel }}</span>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="客户性质">
          <template #default="scope">
            <el-tag :type="scope.row.nature === '3' ? 'danger':'' || scope.row.nature === '4' ? 'success':''">
              <span v-for="item in natureData.data" :key="item.dictCode"
                    v-show="scope.row.nature === item.dictValue">{{ item.dictLabel }}</span>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="负责人" min-width="130" prop="director"/>

        <el-table-column align="center" label="备注" min-width="200" prop="remark"/>

        <el-table-column align="center" label="创建时间" width="180">
          <template #default="scope">
            {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>

        <el-table-column align="center" fixed="right" label="操作" width="110">
          <template #default="scope">
            <el-link :size="store.layoutSize" :underline="false" class="text-xs" :style="{color: store.getTheme}"
                     @click="update(scope.row)">
              <el-icon>
                <EditPen/>
              </el-icon>
              修改
            </el-link>
            <el-link :size="store.layoutSize" :underline="false" class="text-xs ml-3" :style="{color: store.getTheme}"
                     @click="del(scope.row)">
              <el-icon>
                <Delete/>
              </el-icon>
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <el-col class="mt-3 flex justify-end">
      <el-pagination
          :small="store.layoutSize === 'small'"
          :default-current-page="search.pageNum"
          :currentPage="search.pageNum"
          :page-size='search.pageSize'
          :page-sizes="[10, 20, 50, 100]"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="search.total"
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
      />
    </el-col>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form.data" :rules="rules" label-width="80px">
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="form.data.name" :disabled="readonly" placeholder="请输入客户名称"/>
        </el-form-item>
        <el-form-item label="客户电话" prop="phone">
          <el-input v-model="form.data.phone" :disabled="readonly" maxlength="11" placeholder="请输入客户电话"/>
        </el-form-item>
        <el-form-item label="用户性别" prop="sex">
          <el-select v-model="form.data.sex" :disabled="readonly" placeholder="请选择性别">
            <el-option
                v-for="item in sexData.data"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄段" prop="age">
          <el-select v-model="form.data.age" :disabled="readonly" placeholder="请选择年龄段">
            <el-option
                v-for="item in agesData.data"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户来源" prop="source">
          <el-select v-model="form.data.source" :disabled="readonly" placeholder="请选择客户来源">
            <el-option
                v-for="item in sourceData.data"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户性质" prop="nature">
          <el-select v-model="form.data.nature" :disabled="readonly" placeholder="请选择客户性质">
            <el-option
                v-for="item in natureData.data"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="director">
          <el-select v-model="form.data.director" :disabled="readonly" placeholder="请选择负责人">
            <el-option
                v-for="item in usersData.data"
                :key="item.userId"
                :label="item.nickName"
                :value="item.nickName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!(readonly && !form.data.remark)" label="备注" prop="remark">
          <el-input v-model="form.data.remark" :disabled="readonly" placeholder="请输入内容" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div v-if="!readonly" slot="footer" class="flex justify-end">
        <el-button :color="store.getTheme" :loading="btnLoading" type="primary" @click="submitForm(formRef)">确 定
        </el-button>
        <el-button @click="open = false;getSeaData()">取 消</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>

<script setup lang="ts">
import {useStore} from "@/store";
import moment from "moment";
import {reactive, ref} from "vue";
import {getDictData} from "@/api/dictData";
import {downloadCustomerSea, getCustomerSeaData, saveCustomerSea} from "@/api/customerSea";
import {ElMessageBox, ElNotification, FormInstance, FormRules} from "element-plus";
import {getUsersBySelect} from "@/api/user";

const delDisabled = ref(true)

const store = useStore()

const loading = ref(false)

const showSearch = ref(true)

const date = ref([])

const title = ref('')
const open = ref(false)
const formRef = ref<FormInstance>()

//分页方法
function handleCurrentPageChange(val) {
  search.pageNum = val
  getSeaData()
}

//页大小切换
function handlePageSizeChange(val) {
  search.pageSize = val
  getSeaData()
}

const readonly = ref(false)

function add() {
  readonly.value = false
  form.data = {
    director: store.getUser.nickName
  };
  form.data.createBy = store.getUser.userName
  title.value = '添加客户'
  open.value = true
}

function update(val) {
  readonly.value = false
  form.data = val
  form.data.updateBy = store.getUser.userName
  title.value = '修改客户'
  open.value = true
}

//单元格双击事件
function rowClick(val) {
  readonly.value = true
  form.data = val
  title.value = '查看客户'
  open.value = true
}

//赋值负责人下拉框
const usersData = reactive({
  data: []
})
getUsersBySelect().then(result => {
  usersData.data = result.data.data
})

//赋值客户年龄段
const sexData = reactive({
  data: []
})
getDictData({'dictType': 'sys_user_sex'}).then(result => {
  sexData.data = result.data.data
})

//赋值客户年龄段
const agesData = reactive({
  data: []
})
getDictData({'dictType': 'customer_ages'}).then(result => {
  agesData.data = result.data.data
})

const filterSource = reactive({
  data: []
})
//赋值客户来源
const sourceData = reactive({
  data: []
})
getDictData({'dictType': 'cus_source'}).then(result => {
  sourceData.data = result.data.data
})

//赋值客户性质
const natureData = reactive({
  data: []
})
getDictData({'dictType': 'cus_nature'}).then(result => {
  natureData.data = result.data.data
})

const search = reactive({
  name: null,
  director: null,
  source: null,
  nature: null,
  startTime: null,
  endTime: null,
  pageNum: 1,
  pageSize: 10,
  total: 0
})

function clearSearch() {
  search.name = null
  search.director = null
  search.nature = null
  search.startTime = null
  search.endTime = null
  date.value = []
  getSeaData()
}

const tableSeaData = reactive({
  data: []
})
getSeaData()

function getSeaData() {
  loading.value = true
  if (date.value && date.value.length > 0) {
    search.startTime = date.value[0]
    search.endTime = date.value[1]
  } else {
    search.startTime = null
    search.endTime = null
  }
  getCustomerSeaData(search).then(result => {
    search.total = result.data.data.total
    tableSeaData.data = result.data.data.list
    loading.value = false
  })
}

const form = reactive({
  data: {},
})

//时间选择器快捷选择
const shortcuts = [
  {
    text: '上周内',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

const rules = reactive<FormRules>({
  name: [
    {required: true, message: '客户名称不能为空', trigger: 'blur'}
  ],
  director: [
    {required: true, message: '客户负责人不能为空', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '客户电话不能为空', trigger: 'blur'},
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur"
    }
  ],
  age: [
    {required: true, message: '客户性年龄段不能为空', trigger: 'blur'}
  ],
  sex: [
    {required: true, message: '客户性别不能为空', trigger: 'blur'}
  ],
  source: [
    {required: true, message: '客户来源不能为空', trigger: 'blur'}
  ],
  nature: [
    {required: true, message: '客户性质不能为空', trigger: 'blur'}
  ],
})

const btnLoading = ref(false)

//提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      btnLoading.value = true
      saveCustomerSea(form.data).then(result => {
        if (result.data.code === 200) {
          ElNotification({
            message: result.data.msg,
            type: 'success'
          })
        }
        open.value = false
        getSeaData()
        btnLoading.value = false
      })
    }
  })
}

//导出数据
function download() {
  ElMessageBox.confirm('您确定要导出<' + search.total + '>条数据吗？', '警告', {
    confirmButtonText: '导出',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    downloadCustomerSea(search).then(response => {
      let disposition = response.headers['content-disposition'];
      //以下部分有需要优化，如后端返回时没有携带文件后缀名,没有.时会有问题等等
      let filename = disposition ? disposition.substring(disposition.indexOf('=') + 1, disposition.indexOf('.')) : "下载文件";
      let newName = decodeURI(escape(filename))
      let extName = disposition.substring(disposition.indexOf('.') + 1)
      let blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});
      let link = document.createElement("a");
      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("click", false, false);
      link.href = URL.createObjectURL(blob);
      link.download = newName + "." + extName;
      link.style.display = "none";
      document.body.appendChild(link);
      link.click();
      window.URL.revokeObjectURL(link.href);
    })
  })
}
</script>

<style scoped>

</style>
